import React from 'react';
import { browserHistory } from 'react-router'
import { ROOTAPI,ROOTURL,customerInfo } from '../../publicAPI/publicAPI.js'
import stamp from '../img/order/stamp.png'


require('../css/FacialmaskOrderList.css');
class FacialmaskOrderList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            all_orederlist: [ // 全部订单列表
				
			],
			render_orderlist: [ // 需要渲染显示的订单列表

			],
			shop_item: {
				'mobu-a': '进口蚕丝膜布（双层）',
				'mobu-b': '植物纤维天丝膜布（双层）',
				'mobu-c': "竹炭纤维黑膜布（单层）",
				'bolisuan-a': "福瑞达玻尿酸",
				'bolisuan-b': "其他品牌玻尿酸",
				'meiguijingyou-a': "玫瑰精油（润肤）",
				'xunyicaojingyou-a': "薰衣草精油（舒缓宁神）",
				'xiangjing-a': "花香（复合型香味）",
				'xiangjing-b': "果香（复合型香味）",
				'xiangjing-c': "木香（复合型香味）",
				'meibai-a': "美白（传明酸）",
				'zirun-a': "霍霍芭油",
				'zirun-b': "玫瑰果油",
				'fangfuji-a': "防腐剂",
				'baiji': "白芨",
				'luhui': "芦荟",
				'huanggua': "黄瓜",
				'mugua': "木瓜",
				'lvcha': "绿茶",
				'shiliu': "石榴",
				'shuliang-a': "6片/盒",
				'shuliang-b': "12片/盒"
			}
        }
    }
    componentWillMount() {
    }
    componentDidMount() {
    	let _this = this;
    	let callback = function(){
    		_this.getAllOrderList()
    	}
        customerInfo(callback);
    	// this.getAllOrderList();
		// 添加属性使页面可以滑动
		document.getElementById("content").style.height = "auto";
		document.getElementById("content").style.overflow = "scroll";
		document.getElementsByTagName("body")[0].style.height = "auto";
		document.getElementsByTagName("body")[0].style.overflow = "scroll";
		document.getElementsByTagName("html")[0].style.height = "auto";
		document.getElementsByTagName("html")[0].style.overflow = "scroll";
    }
	componentWillUnmount() {
		// 清除页面滑动属性
		document.getElementById("content").style.height = "100%";
		document.getElementById("content").style.overflow = "hidden";
		document.getElementsByTagName("body")[0].style.height = "100%";
		document.getElementsByTagName("body")[0].style.overflow = "hidden";
		document.getElementsByTagName("html")[0].style.height = "100%";
		document.getElementsByTagName("html")[0].style.overflow = "hidden";
	}
	getAllOrderList() {
		let { id } = JSON.parse(localStorage.getItem("customerInfo"));
		let url = ROOTAPI + 'kabuy/contract/search.api';
		let param={
			"limit": 500,
            "where":
                {
                "customerId":
                  	[
                      	["eq",id]
                  	],
                  	"dd":
                  	[
                      	["eq",false]
                  	],
                "order":
                  	[          
                		["tmCreate", "DESC"],   
              		],
                },
        };
        fetch(url, {
                method : 'POST',
                credentials: 'include',
                header: 'application/json; charset=utf-8',
              	body: JSON.stringify(param)
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
						console.log(data)
						let shop_item = this.state.shop_item;
						let order_list = [];
						let order_id = ''; // 订单号
						let composition = []; //成分表
						let state = ''; //支付状态
						let order_time = ''; //订单时间
						let price = '';  //订单价格
						let date_obj = {};
						for (let i = 0; i<data.length; i++) {
							// 订单号
							order_id = data[i].id;
							// 支付状态
							if (data[i].kaStatus == 0) {
								state = '待支付'
							} else {
								state = '交易完成'
							}
							// 订单时间
							date_obj = new Date(data[i].tmCreate);
							order_time = date_obj.getFullYear() + '-' + (date_obj.getMonth()+1) + '-' + date_obj.getDate() + ' ' + this.checkTime(date_obj.getHours()) + ':' + this.checkTime(date_obj.getMinutes());
							// 处理成份表
							composition = [];
							for (let ItemOption_key in data[i].meta.ItemOption) {
								let ItemOption_value = data[i].meta.ItemOption[ItemOption_key];
								for (let shop_item_key in shop_item) {
									if (ItemOption_value == shop_item_key) {
										let shop_item_value = shop_item[shop_item_key]
										composition.push(shop_item_value)
									}
								}
							}
							// 订单价格
							price = data[i].netPay;
							// 添加进数组
							order_list.unshift({
								order_id: order_id,
								composition: composition,
								state: state,
								order_time: order_time,
								price: price
							})
						}
						
                       	this.setState({
                       		all_orederlist: order_list,
							render_orderlist: order_list
                       	})
                    })
                    
                }else{
                    alert("错误")
                }
        })
	}
	checkTime(i) {
		if (i<10) {
			i = '0' + i;
		}
		return i
	}
	chooseOrderList(option) {
		let button_all = document.getElementsByClassName("fm-orderlist-button-all")[0];
		let button_underway = document.getElementsByClassName("fm-orderlist-button-underway")[0];
		if (option == "all") {
			button_all.style.background = "#ffff00";
			button_underway.style.background = "white";
			this.setState({
				render_orderlist: this.state.all_orederlist
			});	
		} else {
			button_all.style.background = "white";
			button_underway.style.background = "#ffff00";
			this.setState({
				render_orderlist: this.state.all_orederlist.filter(function(item) {
					return 	item.state == "待支付";	  	  	
				})
			});
		}
		
	}
	toggleComposition(index) {
		let button = document.getElementsByClassName("fm-orderlist-item-composition-right")[index];
		let composition = document.getElementsByClassName("fm-orderlist-item-composition")[index];
		let text = button.innerHTML;
		if (text == "展开") {
			button.innerHTML = "收起";
			composition.style.height = "auto";
		} else {
			button.innerHTML = "展开";
			composition.style.height = "1.85rem";
		}
		
	}
	toPay(id,price) {
		browserHistory.push({pathname:`/address`,query:{
                                  	id: id,
                                  	netPay: price
                                }})
	}
    render() {
        return (
            <div className="fm-orderlist">
				<div className="fm-orderlist-button">
					<div className="fm-orderlist-button-all" onClick={this.chooseOrderList.bind(this, "all")}>全部</div>
					<div className="fm-orderlist-button-underway" onClick={this.chooseOrderList.bind(this, "underway")}>进行中</div>
					<div className="clear"></div>
				</div>
				<div className="fm-orderlist-list">
					{
						this.state.render_orderlist.map(function(item, index){
							return (
								<div key={index} className="fm-orderlist-item">
									<div className="fm-orderlist-item-title">
										<div className="fm-orderlist-item-title-word1"><span>订单号：</span>{item.order_id}</div>
										<div className="fm-orderlist-item-title-word2">
											{item.state == '待支付' ? <span style={{color: "red"}}>待支付<span className="fm-orderlist-item-title-word2-right" onClick={this.toPay.bind(this,item.order_id,item.price)}>去支付</span></span> : <span style={{color: "#17AA2B"}}>交易完成</span>}
										</div>
										<div className="clear"></div>
									</div>
									<div className="fm-orderlist-item-composition">
										<div className="fm-orderlist-item-composition-left">成份表：</div>
										<div className="fm-orderlist-item-composition-content">
											{
												item.composition.map(function(composition_item, composition_index){
													return (
														<div key={composition_index}>{composition_item}</div>
													)
												},this)
											}
										</div>
										<div className="fm-orderlist-item-composition-right" onClick={this.toggleComposition.bind(this, index)}>展开</div>
										<div className="clear"></div>
									</div>
									<div className="fm-orderlist-item-time">
										<span className="first-span">下单时间：</span>
										<span>{item.order_time}</span>
										<div className="fm-orderlist-item-time-price">&yen;{item.price}</div>
									</div>
									<div className="fm-orderlist-item-hint">
										注：如临时修改收货地址或退款请于公众号联系客服。<br/>
										定制时长约为一周，请耐心等待哦！
									</div>
								</div>
							)
						},this)
					}
				</div>
            </div>
        )
    }
}


export default FacialmaskOrderList;